package es.udc.fic.hamNeggs.manager;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;

import es.udc.fic.hamNeggs.tools.HibernateUtil;

public class AbstractManager {

    protected final Session session = HibernateUtil.getSession();

    protected void save(Object object, Logger LOG) {
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.save(object);
            tx.commit();
            LOG.debug("Insert object " + object.toString() + " on database.");
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            LOG.error("Exception on insert object " + object.toString()
                    + " on database.", e);
        }
    }

    protected void delete(Object object, Logger LOG) {
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.delete(object);
            tx.commit();
            LOG.debug("Deleted object " + object.toString() + " on database.");
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            LOG.error("Exception on deleting " + object.toString()
                    + " on database.", e);
        }

    }

    protected void update(Object object, Logger LOG) {
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            session.update(object);
            tx.commit();
            LOG.debug("Updated object " + object.toString() + " on database.");
        } catch (Exception e) {
            if (tx != null)
                tx.rollback();
            LOG.error("Exception on updating " + object.toString()
                    + " on database.", e);
        }
    }

    public void close() {
        if (session != null) {
            if (session.isConnected())
                session.disconnect();
            if (session.isOpen())
                session.close();
        }
    }

    @Override
    protected void finalize() throws Throwable {
        close();
        super.finalize();
    }

}
